package com.osi.project.common.business;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.*;

import java.util.*;

@Configuration
public class RedisClient {

    @Value("${spring.redis.mode:}")
    private String mode = "single";

    @Value("${spring.redis.host:}")
    private String host;

    @Value("${spring.redis.port:}")
    private Integer port;

    @Value("${spring.redis.password:}")
    private String password;

    @Value("${spring.redis.cluster.nodes:}")
    private List<String> clusterNodes;

    private static JedisPool jedisPool;
    private static JedisCluster jedisCluster;

    // 初始化方法，根据配置文件或环境变量设置mode，并初始化连接池或集群
    public void initialize() {
        if ("single".equalsIgnoreCase(mode)) {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            // 配置连接池参数
            jedisPool = new JedisPool(poolConfig, host, port, 2000, password);
        } else if ("cluster".equalsIgnoreCase(mode)) {
            // 配置集群节点
            // 将List<String>转换为Set<HostAndPort>
            Set<HostAndPort> jedisClusterNodes = new HashSet<>();
            for (String node : clusterNodes) {
                String[] parts = node.split(":");
                String host = parts[0];
                int port = Integer.parseInt(parts[1]);
                jedisClusterNodes.add(new HostAndPort(host, port));
            }
            int timeout = 2000; // 毫秒
            int connectionTimeout = 2000; // 毫秒
            int maxRedirects = 5;
            GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
            jedisCluster = new JedisCluster(jedisClusterNodes, connectionTimeout, timeout, maxRedirects, password, poolConfig);
        }
    }

    // 获取Jedis实例的方法，根据mode返回相应的实例
    public List<Jedis> getJedis() {
         if ("single".equalsIgnoreCase(mode)) {
            if (jedisPool == null) {
                initialize();
            }
            return Arrays.asList(jedisPool.getResource());
        } else {
            if (jedisCluster == null) {
                initialize();
            }
            Map<String, JedisPool> map = jedisCluster.getClusterNodes();

            List<Jedis> jedisList = new ArrayList<>();
            for (JedisPool jedisPool1 : map.values()) {
                jedisList.add(jedisPool1.getResource());
            }
            return jedisList;
        }
    }

    // 关闭资源的方法
    public void closeResources() {
        if ("single".equalsIgnoreCase(mode) && jedisPool != null) {
            jedisPool.close();
        } else if ("cluster".equalsIgnoreCase(mode) && jedisCluster != null) {
            jedisCluster.close();
        }
    }

}
